package com.oocl.ita.servlet;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.ita.po.Person;

/**
 * Servlet implementation class ShowPersonServlet
 */
public class ShowPersonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String RESPFILE = "/ShowPerson.html";

	public ShowPersonServlet() {
		super();
		
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		List<Person> persons = (List<Person>) request.getAttribute("personList");
		String s = addPersonHtml(persons);
		response.getWriter().write(s);
	}

	private String addPersonHtml(List<Person> persons) {
		String html = null;
		try {
			String path = this.getServletContext().getRealPath("/");
			FileInputStream inputStream = new FileInputStream(path+RESPFILE);
			byte[] bs = new byte[inputStream.available()];
			inputStream.read(bs);
			html = new String(bs);
			StringBuffer stringBuffer = new StringBuffer();
			for (Person person : persons) {
				stringBuffer.append("<tr>");
				Field[] fields = person.getClass().getDeclaredFields();
				for (Field field : fields) {
					PropertyDescriptor pd;
					pd = new PropertyDescriptor(field.getName(), person.getClass());
					Method getMethod = pd.getReadMethod();// 获得get方法
					Object o = getMethod.invoke(person);// 执行get方法返回一个Object
					stringBuffer.append("<td>" + o + "</td>");
				}
				stringBuffer.append("</tr>");
			}
			html = html.split("\\{\\{content\\}\\}")[0] + stringBuffer.toString() + html.split("\\{\\{content\\}\\}")[1];
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return html;
	}

}
